package it.java.giw.dataextraction.aleph.wrapper.mymovies;

import it.java.giw.dataextraction.aleph.helper.CSVHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class MymoviesWrapperWorker implements Runnable {

	private LinkedBlockingQueue<String> datasetFiles;
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;
	private HashMap<String, String> attr2xpath;

	private List<String[]> results;
	private CSVHelper helper;

	public MymoviesWrapperWorker(LinkedBlockingQueue<String> datasetFiles, CountDownLatch startSignal, CountDownLatch doneSignal, CSVHelper helper) {
		this.datasetFiles = datasetFiles;
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.results = new ArrayList<String[]>();
		this.attr2xpath = new HashMap<String,String>();
		this.helper = helper;
		initMap();
	}

	private void initMap() {
		/* xpaths di mymovies */
		attr2xpath = new HashMap<String, String>();
		attr2xpath.put("title", "/html/body//div/h1/text()");
		attr2xpath.put("directors", "//div[@class='linkblu']/a[contains(@href, 'http://www.mymovies.it/biografia/?r')]/text()");
		attr2xpath.put("directors2", "//div[@class='linkblu']/a[contains(@href, 'http://www.mymovies.it/dizionario/biblio.asp?r=')]/text()");
		attr2xpath.put("genre", "//div[@class='linkblu']/strong[1]/a/text()");
		attr2xpath.put("year", "/html/body//a[contains(@title, 'Film 1')]/text()");
		attr2xpath.put("year2", "/html/body//a[contains(@title, 'Film 2')]/text()");
		attr2xpath.put("year3", "//*[@id='home_centrale']//span[1][a='film']/../span[2]/a/text()");
		attr2xpath.put("rating", "//span[@class='rating']/text()");
		attr2xpath.put("actors", "//div[@class='linkblu']/a[contains(@href, 'http://www.mymovies.it/biografia/?a')]/text()");
		attr2xpath.put("actors2", "//div[@class='linkblu']/a[contains(@href, 'http://www.mymovies.it/dizionario/biblio.asp?a=')]/text()");
		attr2xpath.put("poster", "/html/body//a[contains(@title, 'Locandina')]/img/@src");
		attr2xpath.put("year2moviesLink", "/html/body//a[contains(@title, 'Film 1')]/@href");
		attr2xpath.put("year2moviesLink2", "/html/body//a[contains(@title, 'Film 2')]/@href");
		attr2xpath.put("year2moviesLink3", "//*[@id='home_centrale']//span[1][a='film']/../span[2]/a/@href");
		/* fine xpaths mymovies */
	}

	public void run() {
		try {
			startSignal.await();
			while(!datasetFiles.isEmpty()){
				/* create webClient and set options to get only HTML */
				final WebClient webClient = new WebClient();
				//		webClient.getOptions().setThrowExceptionOnScriptError(false);
				webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
				webClient.getOptions().setCssEnabled(false);
				webClient.getOptions().setJavaScriptEnabled(false);
				webClient.getOptions().setAppletEnabled(false);

				HtmlPage page;
				try {
					String[] info = new String[10];
					String filename = datasetFiles.poll();
					page = webClient.getPage("file:///C:/Users/Roberto/giw2/AlephDataExtractor/download/"+filename);
					System.out.println(filename);
					//				    System.out.println(page.getByXPath("//h1[1]/text()"));
					info[0] = filename;
					//title
					info[1] = page.getByXPath(attr2xpath.get("title")).get(0).toString();
					//director(s)
					info[2] = "";
					for (Object director : page.getByXPath(attr2xpath.get("directors")))
						info[2] += director.toString()+";";
					if (info[2].equals("")){
						for (Object director : page.getByXPath(attr2xpath.get("directors2")))
							info[2] += director.toString()+";";
					}
					//genre
					info[3] = page.getByXPath(attr2xpath.get("genre")).get(0).toString();
					//year
					info[4] = "";
					List<?> l = page.getByXPath(attr2xpath.get("year"));
					if (!l.isEmpty())
						info[4] = l.get(0).toString();
					else{
						l = page.getByXPath(attr2xpath.get("year2"));
						if (!l.isEmpty())
							info[4] = l.get(0).toString();
						else{
							l = page.getByXPath(attr2xpath.get("year3"));
							if (!l.isEmpty())
								info[4] = l.get(0).toString();
						}
					}
					//rating
					info[5] = "n.d.";
					l = page.getByXPath(attr2xpath.get("rating"));
					if (!l.isEmpty())
						info[5] = l.get(0).toString();
					//actors
					info[6] = "";
					for (Object actor : page.getByXPath(attr2xpath.get("actors")))
						info[6] += actor.toString()+";";
					if (info[6].equals("")){
						for (Object director : page.getByXPath(attr2xpath.get("actors2")))
							info[6] += director.toString()+";";
					}
					//poster
					info[7] = "";
					l = page.getByXPath(attr2xpath.get("poster"));
					if (!l.isEmpty())
						info[7] = ((DomAttr)l.get(0)).getValue();
					//link
					info[8] = "";
					l = page.getByXPath(attr2xpath.get("year2moviesLink"));
					if (!l.isEmpty())
						info[8] = ((DomAttr)l.get(0)).getValue();
					else{
						l = page.getByXPath(attr2xpath.get("year2moviesLink2"));
						if (!l.isEmpty())
							info[8] = ((DomAttr)l.get(0)).getValue();
						else{
							l = page.getByXPath(attr2xpath.get("year2moviesLink3"));
							if (!l.isEmpty())
								info[8] = ((DomAttr)l.get(0)).getValue();
						}
					}
					results.add(info);

				} catch (FailingHttpStatusCodeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IndexOutOfBoundsException e){
					System.err.println("Errore parsing");
				}
			}
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			doneSignal.countDown();
		}finally{
			try {
				for(String[] row : results)
					helper.writeCSV(row,"Collection MyMovies.csv");
			} catch (Exception e) {
				e.printStackTrace();
			}
			doneSignal.countDown();
		}
	}
}
